﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace WebApi.Common
{
    public class FfmpegMgr
    {
        public static int GetMediaTimeLenMinute(string path)
        {
            int duration = 0;
            string ffmpeg = $"{ServiceBase.Get<HostingEnvironment>().WebRootPath}\\Ffmpeg\\bin\\ffmpeg.exe"; //ffmpeg路径
            string curr_duration = "00:00:00"; //视频时长,格式00:08:50
            System.Diagnostics.Process p = new System.Diagnostics.Process();
            p.StartInfo.FileName = ffmpeg;
            p.StartInfo.Arguments = " -i " + path;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.CreateNoWindow = true;
            p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
            p.StartInfo.RedirectStandardError = true;
            p.Start();
            StreamReader errorreader = p.StandardError;
            p.WaitForExit(1000);
            string result = errorreader.ReadToEnd();
            try
            {
                curr_duration = result.Substring(result.IndexOf("Duration: ") + ("Duration: ").Length, ("00:00:00").Length);
                //do something

            }
            catch (Exception ex)
            {
                //do something
            }
            duration = Convert.ToInt32(curr_duration.Split(':')[0]) * 3600 + Convert.ToInt32(curr_duration.Split(':')[1]) * 60 + Convert.ToInt32(curr_duration.Split(':')[2]);
            return duration;
        }

    }
}
